package com.lxl.xm.chat;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.zhipu.oapi.ClientV4;
import com.zhipu.oapi.Constants;

import com.zhipu.oapi.service.v4.model.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


/**
 * 智谱ai调用客户端
 */
@Component
public class V4OkHttpClient {
    private static final String API_KEY = "e7f119e3e149cd7a0451459c0400af0c";

    private static final String API_SECRET = "jIMSeIyotgyqoFTj";

    private static final ClientV4 client = new ClientV4.Builder(API_KEY,API_SECRET).build();

    private static final ObjectMapper mapper = defaultObjectMapper();

    //自定义请求id
    private static final String requestIdTemplate = "lxlDemo-%d";

    public static ObjectMapper defaultObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        mapper.addMixIn(ChatFunction.class, ChatFunctionMixIn.class);
        mapper.addMixIn(ChatCompletionRequest.class, ChatCompletionRequestMixIn.class);
        mapper.addMixIn(ChatFunctionCall.class, ChatFunctionCallMixIn.class);
        return mapper;
    }

    /**
     * 同步调用
     */
//    public String testInvoke(String question) {
//        List<ChatMessage> messages = new ArrayList<>();
//        ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(), question);
//        messages.add(chatMessage);
//        String requestId = String.format(requestIdTemplate, System.currentTimeMillis());
//        // 函数调用参数构建部分
//        List<ChatTool> chatToolList = new ArrayList<>();
//        ChatTool chatTool = new ChatTool();
//        chatTool.setType(ChatToolType.RETRIEVAL.value());
//        Retrieval retrieval = new Retrieval();
//        retrieval.setKnowledge_id("1767061800299433984");
//        retrieval.setPrompt_template("从文档{{knowledge}}中找问题{{question}}的答案，找到答案就仅使用文档语句回答问题,不要复述问题，直接开始回答。");
//        chatTool.setRetrieval(retrieval);
//        chatToolList.add(chatTool);
////        List<ChatTool> chatToolList = new ArrayList<>();
////        ChatTool chatTool = new ChatTool();
////        chatTool.setType(ChatToolType.FUNCTION.value());
////        ChatFunctionParameters chatFunctionParameters = new ChatFunctionParameters();
////        chatFunctionParameters.setType("object");
////        Map<String, Object> properties = new HashMap<>();
////        properties.put("location", new HashMap<String, Object>() {{
////            put("type", "string");
////            put("description", "城市，如：北京");
////        }});
////        properties.put("unit", new HashMap<String, Object>() {{
////            put("type", "string");
////            put("enum", new ArrayList<String>() {{
////                add("celsius");
////                add("fahrenheit");
////            }});
////        }});
////        chatFunctionParameters.setProperties(properties);
////        ChatFunction chatFunction = ChatFunction.builder()
////                .name("get_weather")
////                .description("Get the current weather of a location")
////                .parameters(chatFunctionParameters)
////                .build();
////        chatTool.setFunction(chatFunction);
////        chatToolList.add(chatTool);
//        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
//                .model(Constants.ModelChatGLM4)
//                .stream(Boolean.FALSE)
//                .invokeMethod(Constants.invokeMethod)
//                .messages(messages)
//                .requestId(requestId)
//                .tools(chatToolList)
//                .toolChoice("auto")
//                .build();
//        ModelApiResponse invokeModelApiResp = client.invokeModelApi(chatCompletionRequest);
//        String content = "";
//        List<Choice> choices = invokeModelApiResp.getData().getChoices();
//        Choice choice = choices.get(0);
//        try {
//            content = (String) choice.getMessage().getContent();
//            System.out.println("model output:" + mapper.writeValueAsString(invokeModelApiResp));
//        } catch (JsonProcessingException e) {
//            e.printStackTrace();
//        }
//        return content;
//    }


    public static ModelApiResponse Invoke(String question) {
        List<ChatMessage> messages = new ArrayList<>();
        ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(), question);
        messages.add(chatMessage);
        String requestId = String.format(requestIdTemplate, System.currentTimeMillis());
        // 函数调用参数构建部分
        List<ChatTool> chatToolList = new ArrayList<>();
        ChatTool chatTool = new ChatTool();
        chatTool.setType(ChatToolType.RETRIEVAL.value());
        Retrieval retrieval = new Retrieval();
        retrieval.setKnowledge_id("1767061800299433984");
        retrieval.setPrompt_template("从文档{{knowledge}}中找问题{{question}}的答案，找到答案就仅使用文档语句回答问题，不要复述问题，直接回答。");
        chatTool.setRetrieval(retrieval);
        chatToolList.add(chatTool);
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model(Constants.ModelChatGLM4)
                .stream(Boolean.FALSE)
                .invokeMethod(Constants.invokeMethod)
                .messages(messages)
                .requestId(requestId)
                .tools(chatToolList)
                .toolChoice("auto")
                .build();
        ModelApiResponse invokeModelApiResp = client.invokeModelApi(chatCompletionRequest);
        String content = "";
        try {
            content = mapper.writeValueAsString(invokeModelApiResp.getData()
                    .getChoices().get(0).getMessage().getContent());
            content = StringUtils.replace(content,"\\n\\n","");
            content = StringUtils.replace(content,"\\n","");

        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return invokeModelApiResp;
    }

}
